package algorithm.middle;

import pojo.Node;
import pojo.TreeNode;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 完全二叉树 是每一层（除最后一层外）都是完全填充（即，节点数达到最大）的，并且所有的节点都尽可能地集中在左侧。
 *
 * 设计一种算法，将一个新节点插入到一个完整的二叉树中，并在插入后保持其完整。
 *
 *
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/complete-binary-tree-inserter
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class CBTInserter919 {

    Queue<TreeNode> quine;
    TreeNode root;

    public CBTInserter919(TreeNode root) {
        this.root = root;
        quine = new LinkedList<>();
        quine.add(root);
        while (!quine.isEmpty()) {
            TreeNode peek = quine.peek();
            if (peek.left != null) {
                quine.add(peek.left);
            }
            if (peek.right != null) {
                quine.add(peek.right);
            }
            if (peek.left != null && peek.right != null) {
                quine.poll();
            } else {
                break;
            }
        }
    }

    public int insert(int val) {
        TreeNode newNode = new TreeNode(val);
        TreeNode peek = quine.peek();
        if (peek.left == null) {
            peek.left = newNode;
        } else  if (peek.right == null) {
            peek.right = newNode;
            quine.poll();
        }
        quine.add(newNode);
        return peek.val;
    }

    public TreeNode get_root() {
        return root;
    }


    /**
     * 使用二进制表示
     */
    class CBTInserter {
        int cnt;
        TreeNode root;

        public CBTInserter(TreeNode root) {
            this.cnt = 0;
            this.root = root;

            Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
            queue.offer(root);

            while (!queue.isEmpty()) {
                ++cnt;
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }

        public int insert(int val) {
            ++cnt;
            TreeNode child = new TreeNode(val);
            TreeNode node = root;
            int highbit = 31 - Integer.numberOfLeadingZeros(cnt);
            for (int i = highbit - 1; i >= 1; --i) {
                if ((cnt & (1 << i)) != 0) {
                    node = node.right;
                } else {
                    node = node.left;
                }
            }
            if ((cnt & 1) != 0) {
                node.right = child;
            } else {
                node.left = child;
            }
            return node.val;
        }

        public TreeNode get_root() {
            return root;
        }
    }


}
